package cn.xuchunh.campusbbs.net;

import android.content.Context;
import android.text.TextUtils;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response.ErrorListener;
import com.android.volley.toolbox.Volley;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import cn.xuchunh.campusbbs.AppContext;
import cn.xuchunh.campusbbs.api.ApiConstant;
import cn.xuchunh.campusbbs.bean.User;
import cn.xuchunh.campusbbs.net.params.TopicListParams;
import cn.xuchunh.campusbbs.storage.sp.SharedPreferenceManager;
import cn.xuchunh.campusbbs.utils.AppUtil;
import cn.xuchunh.campusbbs.utils.DeviceUtil;
import cn.xuchunh.campusbbs.utils.StringUtil;

/**
 * Created by XuChunH on 2015/8/31.
 */
public class HttpRequestManager {
    private static HttpRequestManager instance;
    private RequestQueue requestQueue;
    private String mcForumType = "7";
    private String mcPlatType = "1";
    private Map<String, String> httpParams;
    private String serverPath;
    private String cookies;

    public synchronized static HttpRequestManager getInstance(Context context) {
        if (instance == null) {
            instance = new HttpRequestManager(context.getApplicationContext());
        }
        return instance;
    }

    private HttpRequestManager(Context context) {
        httpParams = new HashMap<>();
        SharedPreferenceManager sharedPreferenceManager = SharedPreferenceManager.getInstance();
        httpParams.put("appName", sharedPreferenceManager.getAppName());
        httpParams.put("packageName", sharedPreferenceManager.getPackageName());
        httpParams.put("sdkVersion", sharedPreferenceManager.getSdkVersion());
        httpParams.put("forumKey", sharedPreferenceManager.getForumKey());

        httpParams.put("forumType", mcForumType);
        httpParams.put("imei", DeviceUtil.getIMEI());
        httpParams.put("platType", mcPlatType);
        httpParams.put("imsi", DeviceUtil.getIMSI());
        httpParams.put("sdkType", "");

        serverPath = String.format(ApiConstant.SERVER_PATH_FORMAT, sharedPreferenceManager.getServerDomain());

        requestQueue = Volley.newRequestQueue(context.getApplicationContext());
        requestQueue.start();
    }

    @SuppressWarnings("unchecked")
    private void doPostRequest(String url, Map<String, String> params,
                               XJsonListener listener,
                               ErrorListener errorListener, String tag) {
        XJsonRequest xJsonRequest = new XJsonRequest(Request.Method.POST, serverPath + url, null,
                params, listener, errorListener);
        if (!TextUtils.isEmpty(tag)) {
            xJsonRequest.setTag(tag);
        }
        requestQueue.add(xJsonRequest);
    }

    public void cancelRequest(String tag) {
        if (TextUtils.isEmpty(tag)) {
            return;
        }
        requestQueue.cancelAll(tag);
    }

    public void stop() {
        if (requestQueue != null) {
            requestQueue.stop();
            requestQueue = null;
            instance = null;
        }
    }

    public void addParams(String name, String value) {
        if (TextUtils.isEmpty(name) || TextUtils.isEmpty(value)) {
            return;
        }
        httpParams.put(name, value);
    }

    public void setToken(String token) {
        if (TextUtils.isEmpty(token)) {
            return;
        }
        httpParams.put("accessToken", token);
    }

    public void setSecret(String secret) {
        if (TextUtils.isEmpty(secret)) {
            return;
        }
        httpParams.put("accessSecret", secret);
    }

    /**
     * 登录
     *
     * @param userName
     * @param password
     * @param listener
     * @param errorListener
     * @param tag
     */
    public void login(String userName, String password,
                      XJsonListener<User> listener, ErrorListener errorListener, String tag) {
        Map<String, String> params = new HashMap<>();
        params.put("username", userName);
        params.put("apphash", AppUtil.getHash());
        params.put("type", "login");
        params.put("password", password);
        params.putAll(httpParams);
        doPostRequest(ApiConstant.SERVER_LOGIN, params, listener, errorListener, tag);
    }

    /**
     * 社区，获取板块
     *
     * @param listener
     * @param errorListener
     * @param tag
     */
    public void loadForumList(XJsonListener listener,
                              ErrorListener errorListener, String tag) {
        Map<String, String> params = new HashMap<>();
        params.put("apphash", AppUtil.getHash());
        params.putAll(httpParams);
        doPostRequest(ApiConstant.SERVER_FORUM_LIST, params, listener, errorListener, tag);
    }


    /**
     * 获取子版块
     *
     * @param forumId
     * @param listener
     * @param errorListener
     * @param tag
     */
    public void loadChildForumList(int forumId,
                                   XJsonListener listener,
                                   ErrorListener errorListener, String tag) {
        Map<String, String> params = new HashMap<>();
        params.put("apphash", AppUtil.getHash());
        params.put("fid", forumId + "");
        params.putAll(httpParams);
        doPostRequest(ApiConstant.SERVER_FORUM_LIST, params, listener, errorListener, tag);
    }

    /**
     * 获取帖子
     *
     * @param topicListParams
     * @param listener
     * @param errorListener
     * @param tag
     */
    public void loadTopicList(TopicListParams topicListParams,
                              XJsonListener listener,
                              ErrorListener errorListener, String tag) {
        if (topicListParams == null) {
            return;
        }
        Map<String, String> params = new HashMap<>();
        params.put("sortby", topicListParams.getSort());
        params.put("boardId", topicListParams.getBoardId() + "");
        params.put("apphash", AppUtil.getHash());
        params.put("pageSize", topicListParams.getPageSize() + "");
        params.put("filterId", topicListParams.getFilterId() + "");
        params.put("page", topicListParams.getPage() + "");
        params.put("topOrder", topicListParams.getTopOrder() + "");
        params.put("longitude", "103.9375991821289");
        params.put("latitude", "30.76241111755371");
        params.put("isImageList", topicListParams.getIsImageList() + "");
        params.put("filterType", topicListParams.getFilterType() + "");
        params.putAll(httpParams);
        doPostRequest(ApiConstant.SERVER_TOPIC_LIST, params, listener, errorListener, tag);
    }

    /**
     * 帖子详情
     *
     * @param pageSize
     * @param topicId
     * @param authorId
     * @param forumId
     * @param page
     * @param listener
     * @param errorListener
     * @param tag
     */
    public void loadTopicDetail(int pageSize, int topicId, int authorId, int forumId, int page,
                                XJsonListener listener,
                                ErrorListener errorListener, String tag) {

        Map<String, String> params = new HashMap<>();
        params.put("apphash", AppUtil.getHash());
        params.put("pageSize", pageSize + "");
        params.put("topicId", topicId + "");
        params.put("authorId", authorId + "");
        params.put("boardId", forumId + "");
        params.put("page", page + "");
        params.putAll(httpParams);
        doPostRequest(ApiConstant.SERVER_TOPIC_DETAIL, params, listener, errorListener, tag);
    }

    /**
     * 搜索
     *
     * @param pageSize
     * @param page
     * @param query
     * @param searchid
     * @param listener
     * @param errorListener
     * @param tag
     */
    @SuppressWarnings("unchecked")
    public void search(int pageSize, int page, String query, int searchid,
                       XJsonListener listener,
                       ErrorListener errorListener, String tag) {
        Map<String, String> params = new HashMap<>();
        params.put("apphash", AppUtil.getHash());
        params.put("searchid", searchid + "");
        params.put("pageSize", pageSize + "");
        params.put("baseUrl", "http://" + ApiConstant.SERVER_DOMAIN);
        params.put("keyword", query);
        params.put("baiketype", "1");
        params.put("page", page + "");
        params.putAll(httpParams);
        XJsonRequest simpleHttpRequest = new XJsonRequest(
                Request.Method.POST, ApiConstant.SERVER_SEARCH, null, params, listener, errorListener);
        if (!TextUtils.isEmpty(tag)) {
            simpleHttpRequest.setTag(tag);
        }
        requestQueue.add(simpleHttpRequest);
    }

    /**
     * 用户信息
     *
     * @param userId
     * @param listener
     * @param errorListener
     * @param tag
     */
    public void loadUserInfo(int userId, XJsonListener listener, ErrorListener errorListener, String tag) {
        Map<String, String> params = new HashMap<>();
        params.put("apphash", AppUtil.getHash());
        params.put("userId", userId + "");
        params.putAll(httpParams);
        doPostRequest(ApiConstant.SERVER_LOAD_USER_INFO, params, listener, errorListener, tag);
    }

    /**
     * 用户的帖子
     *
     * @param userId
     * @param page
     * @param pageSize
     * @param listener
     * @param errorListener
     * @param tag
     */
    public void loadUserTopicList(int userId, int page, int pageSize, XJsonListener listener, ErrorListener errorListener, String tag) {
        Map<String, String> params = new HashMap<>();
        params.put("apphash", AppUtil.getHash());
        params.put("uid", userId + "");
        params.put("type", "topic");
        params.put("page", page + "");
        params.put("pageSize", pageSize + "");
        params.putAll(httpParams);
        doPostRequest(ApiConstant.SERVER_LOAD_USER_TOPICS, params, listener, errorListener, tag);
    }

    /**
     * 相册
     *
     * @param userId
     * @param page
     * @param pageSize
     * @param listener
     * @param errorListener
     * @param tag
     */
    public void loadUserAlbumList(int userId, int page, int pageSize, XJsonListener listener, ErrorListener errorListener, String tag) {
        Map<String, String> params = new HashMap<>();
        params.put("apphash", AppUtil.getHash());
        params.put("uid", userId + "");
        params.put("page", page + "");
        params.put("pageSize", pageSize + "");
        params.putAll(httpParams);
        doPostRequest(ApiConstant.SERVER_LOAD_USER_ALBUM_LIST, params, listener, errorListener, tag);
    }

    /**
     * 相册里的图片
     *
     * @param userId
     * @param albumId
     * @param page
     * @param pageSize
     * @param listener
     * @param errorListener
     * @param tag
     */
    public void loadUserPhotoList(int userId, int albumId, int page, int pageSize, XJsonListener listener, ErrorListener errorListener, String tag) {
        Map<String, String> params = new HashMap<>();
        params.put("apphash", AppUtil.getHash());
        params.put("uid", userId + "");
        params.put("page", page + "");
        params.put("pageSize", pageSize + "");
        params.put("albumId", albumId + "");
        params.putAll(httpParams);
        doPostRequest(ApiConstant.SERVER_LOAD_USER_PHOTO_LIST, params, listener, errorListener, tag);
    }

    /**
     * 收藏
     *
     * @param id
     * @param action
     * @param listener
     * @param errorListener
     * @param tag
     */
    public void favorite(int id, String action, XJsonListener listener, ErrorListener errorListener, String tag) {
        Map<String, String> params = new HashMap<>();
        params.put("apphash", AppUtil.getHash());
        params.put("idType", "tid");
        params.put("id", id + "");
        params.put("action", action);
        params.putAll(httpParams);
        doPostRequest(ApiConstant.SERVER_TOPIC_FAVORITE, params, listener, errorListener, tag);
    }

    public boolean savePicture(String path) {

        if (TextUtils.isEmpty(path)) {
            return false;
        }
        boolean result = true;
        InputStream in = null;
        FileOutputStream outputStream = null;
        try {
            URL url = new URL(path);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(5 * 1000);
            connection.setReadTimeout(30 * 1000);
            in = new BufferedInputStream(connection.getInputStream());
            String savePath = AppUtil.getPicturesPath(AppContext.getInstance()) + StringUtil.getNameFromUrl(path);
            File file = new File(savePath);
            if (!file.exists()) {
                file.createNewFile();
            }
            outputStream = new FileOutputStream(file);
            byte[] buffer = new byte[1024];
            int len;
            while ((len = in.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }
            outputStream.flush();
        } catch (MalformedURLException ignored) {
            result = false;
        } catch (IOException e) {
            result = false;
        } finally {
            try {

                if (in != null) {
                    in.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
            }
        }
        return result;
    }

    public String getCookies() {
        return cookies;
    }

    public void setCookies(String cookies) {
        this.cookies = cookies;
    }
}
